package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.utils.MediaLoadManager;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.SelVideoAdapter;
import flc.ast.adapter.SelVideoAdapter1;
import flc.ast.databinding.ActivitySearchBinding;
import flc.ast.dialog.EditDialog;
import flc.ast.dialog.InfoDialog;
import flc.ast.dialog.RenameDialog;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.constant.Extra;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.ContactUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;

public class SearchActivity extends BaseAc<ActivitySearchBinding> {

    private SelVideoAdapter videoAdapter;
    private SelVideoAdapter1 videoAdapter1;
    private List<SelectMediaEntity> listShow = new ArrayList<>();
    private boolean hasLineStyle = true;


    public static void start(Context context, boolean hasLineStyle) {
        Intent intent = new Intent(context, SearchActivity.class);
        intent.putExtra(Extra.DATA, hasLineStyle);
        context.startActivity(intent);
    }

    @Override
    protected int onCreate() {
        return R.layout.activity_search;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivSearchBack.setOnClickListener(v -> onBackPressed());

        Intent intent = getIntent();
        hasLineStyle = intent.getBooleanExtra(Extra.DATA, true);

        mDataBinding.rvSearchList.setLayoutManager(new LinearLayoutManager(mContext));
        videoAdapter = new SelVideoAdapter();
        mDataBinding.rvSearchList.setAdapter(videoAdapter);
        videoAdapter.addChildClickViewIds(R.id.ivSelVideoItemEdit);
        videoAdapter.setOnItemChildClickListener(this);
        videoAdapter.setOnItemClickListener(this);

        videoAdapter1 = new SelVideoAdapter1();
        videoAdapter1.addChildClickViewIds(R.id.ivSelVideoItemEdit);
        videoAdapter1.setOnItemChildClickListener(this);
        videoAdapter1.setOnItemClickListener(this);
        mDataBinding.etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String content = s.toString();
                if (hasLineStyle) {
                    if (TextUtils.isEmpty(content)) {
                        videoAdapter.setList(listShow);
                        videoAdapter.hasQuery = false;
                    } else {
                        videoAdapter.setList(filterName(content));
                        videoAdapter.hasQuery = true;
                        videoAdapter.keyWord = content;
                    }
                    videoAdapter.notifyDataSetChanged();
                } else {
                    if (TextUtils.isEmpty(content)) {
                        videoAdapter1.setList(listShow);
                        videoAdapter1.hasQuery = false;
                    } else {
                        videoAdapter1.setList(filterName(content));
                        videoAdapter1.hasQuery = true;
                        videoAdapter1.keyWord = content;
                    }
                    videoAdapter1.notifyDataSetChanged();

                }
            }
        });
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        switch (view.getId()) {
            case R.id.ivSelVideoItemEdit://编辑
                showEditDialog(position);
                break;
        }
    }

    @Override
    protected void initData() {
        getPermission();
    }

    private void getPermission() {
        StkPermissionHelper.reqManageExternalStoragePermission()
                .reqPermissionDesc(getString(R.string.get_video_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        getData();
                    }

                    @Override
                    public void onDenied(boolean needGoSettings) {
                        mDataBinding.rvSearchList.setVisibility(View.GONE);
                    }
                }).request();
    }

    //获取视频和图片数据
    private void getData() {
        listShow.clear();
        RxUtil.create(new RxUtil.Callback<List<SelectMediaEntity>>() {
            @Override
            public void doBackground(ObservableEmitter<List<SelectMediaEntity>> emitter) {
                List<SelectMediaEntity> listSys = MediaLoadManager.loadAllMediaData(mContext, PhotoConfig.Mode.VIDEO);
                emitter.onNext(listSys);
            }

            @Override
            public void accept(List<SelectMediaEntity> selectMediaEntities) {
                if (selectMediaEntities.size() > 0) {
                    listShow.addAll(selectMediaEntities);
                    videoAdapter.setList(selectMediaEntities);
                    videoAdapter1.setList(selectMediaEntities);
                    mDataBinding.rvSearchList.setVisibility(View.VISIBLE);
                } else {
                    mDataBinding.rvSearchList.setVisibility(View.GONE);
                }
            }
        });
    }

    private List<SelectMediaEntity> filterName(String key) {
        List<SelectMediaEntity> data = new ArrayList<>();
        for (SelectMediaEntity item : listShow) {
            if (item.getMediaName().contains(key != null ? key.toString() : null)) {
                data.add(item);
            }
        }
        return data;
    }

    private void showEditDialog(int position) {
        EditDialog dialog = new EditDialog(mContext);
        dialog.selectMediaEntity = listShow.get(position);
        dialog.setListener(new EditDialog.Ilistener() {
            @Override
            public void clickRename() {
                showRenameDialog(position);
            }

            @Override
            public void clickShare() {
                IntentUtil.shareVideo(mContext, listShow.get(position).getPath());
            }

            @Override
            public void clickAddPrivacyFolder() {
                String filePath = FileUtil.generateFilePath(Content.myPrivacyVideo, "." + FileUtils.getFileExtension(listShow.get(position).getPath()));
                FileUtils.copy(listShow.get(position).getPath(), filePath);
                ToastUtils.showShort(getString(R.string.add_suc));
            }

            @Override
            public void clickInfo() {
                showInfoDialog(position);
            }

            @Override
            public void clickDelete() {
                getDeletePermission(position);
            }
        });
        dialog.show();
    }

    private void showRenameDialog(int position) {
        RenameDialog dialog = new RenameDialog(mContext);
        dialog.title = getString(R.string.file_rename);
        dialog.hint = getString(R.string.please_input_folder_name_text);
        dialog.setListener(new RenameDialog.Ilistener() {
            @Override
            public void clickRename(String name) {
                FileUtils.rename(listShow.get(position).getPath(), name + "." + FileUtils.getFileExtension(listShow.get(position).getPath()));
                getData();
            }
        });
        dialog.show();
    }

    //获取权限
    private void getDeletePermission(int position) {
        StkPermissionHelper.reqManageExternalStoragePermission()
                .reqPermissionDesc(getString(R.string.get_all_storage_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        delete(position);
                    }
                })
                .request();
    }

    private void delete(int position) {
        showDialog(getString(R.string.delete_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        //从此文件夹删除
                        mContext.getContentResolver().delete(Uri.parse(listShow.get(position).getUri()), null, null);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        getData();
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.delete_suc));
                    }
                });
            }
        }, 1000);
    }

    private void showInfoDialog(int position) {
        InfoDialog dialog = new InfoDialog(mContext);
        dialog.videoPath = listShow.get(position).getPath();
        dialog.show();
    }

}